import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { checkValidMoves, makeMove, checkWinner } from '@/utils/gameLogic'

export const useGameStore = defineStore('othello', () => {
  // 游戏状态
  const board = ref(Array(8).fill().map(() => Array(8).fill(null)))
  const currentPlayer = ref('black') // 'black' 或 'white'
  const gameStatus = ref('playing') // 'playing', 'won', 'draw'
  const winner = ref(null)
  const lastMove = ref(null) // 记录最后一步 {row, col, player}
  
  // 初始化游戏
  const initGame = () => {
    // 清空棋盘
    board.value = Array(8).fill().map(() => Array(8).fill(null))
    
    // 设置初始棋子
    board.value[3][3] = 'white'
    board.value[3][4] = 'black'
    board.value[4][3] = 'black'
    board.value[4][4] = 'white'
    
    currentPlayer.value = 'black'
    gameStatus.value = 'playing'
    winner.value = null
    lastMove.value = null
  }
  
  // 切换玩家
  const switchPlayer = () => {
    currentPlayer.value = currentPlayer.value === 'black' ? 'white' : 'black'
  }
  
  // 执行落子
  const placePiece = (row, col) => {
    if (gameStatus.value !== 'playing') return false
    
    const validMoves = checkValidMoves(board.value, currentPlayer.value)
    if (!validMoves.some(move => move.row === row && move.col === col)) {
      return false
    }
    
    // 执行落子并翻转棋子
    const flipped = makeMove(board.value, row, col, currentPlayer.value)
    if (flipped.length === 0) return false
    
    // 记录最后一步
    lastMove.value = { row, col, player: currentPlayer.value }
    
    // 检查游戏是否结束
    const nextPlayerValidMoves = checkValidMoves(board.value, currentPlayer.value === 'black' ? 'white' : 'black')
    if (nextPlayerValidMoves.length === 0) {
      const currentPlayerValidMoves = checkValidMoves(board.value, currentPlayer.value)
      if (currentPlayerValidMoves.length === 0) {
        // 双方都无可落子点，游戏结束
        const result = checkWinner(board.value)
        gameStatus.value = 'won'
        winner.value = result.winner
      } else {
        // 对方无可落子点，当前玩家继续
        // 不切换玩家
        return true
      }
    }
    
    // 切换玩家
    switchPlayer()
    return true
  }
  
  // 计算属性：当前玩家的有效落子位置
  const validMoves = computed(() => {
    return checkValidMoves(board.value, currentPlayer.value)
  })
  
  // 计算属性：棋盘状态
  const boardState = computed(() => board.value)
  
  return {
    boardState,
    currentPlayer,
    gameStatus,
    winner,
    validMoves,
    lastMove,
    initGame,
    placePiece
  }
})
